<template>
  <div>
    <el-col :span="24" class="title-row">
      <span :style="{ color: theme }">| 新增道路面</span>
    </el-col>
    <el-form
      id="elForm"
      ref="elForm"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="92px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="道路名称" prop="name">
            <el-input
              v-model="formData.name"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="道路功能" prop="roadfunction">
            <el-select
              v-model="formData.roadfunction"
              placeholder="请选择道路功能"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in dict.type.sys_roadfunction"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        class="footer"
        size="medium"
        style="display: flex; justify-content: center"
      >
        <el-button type="primary" @click="submitForm" icon="el-icon-check"
          >提交</el-button
        >
        <el-button @click="resetForm">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-circle-close"
          @click="cancel"
          >返回</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Sketch from "@arcgis/core/widgets/Sketch";
import { v4 as uuidv4 } from "uuid";
export default {
  props: {
    paramObj: { default: () => {} },
    mapview: { default: () => {} },
  },
  inject: ["toggleComponent"],
  dicts: ["sys_roadfunction"],
  computed: {
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  data() {
    return {
      // 必须给formData对象的属性设置对应空值，否则重置后无法输入数据
      formData: {
        name: undefined,
        code: undefined,
        roadfunction: undefined,
      },
      rules: undefined,
      featureLayer: undefined,
      selectedGraphic: undefined,
      udpateGraphicsLayer: undefined,
      addGraphics: [],
      roadfeature: undefined,
    };
  },
  activated() {
    let _self = this;
    console.log(_self.paramObj);
    _self.roadfeature = _self.paramObj.roadfeature;
    _self.featureLayer = _self.paramObj.featureLayer;
    // _self.formData.name = _self.paramObj.roadname;
    _self.formData.code = _self.roadfeature.attributes.code;
    // 显示图形编辑面板
    _self.addGeometry();
    // _self.formData = {
    //   name: "道路名称",
    //   code: "ba695de8-1ef4-4e4f-86fe-f14a889e2609",
    //   roadnumber: "道路编号",
    //   roadclass_js: "1",
    //   length: "3443",
    //   width: "434",
    //   endpoint: "止点",
    //   startpoint: "起点",
    //   note: "备注",
    //   cleancompany: "未分配",
    //   data_status: "1",
    // };
  },
  deactivated() {
    this.cancel();
  },
  methods: {
    // 更新空间位置
    addGeometry() {
      let _self = this;
      _self.udpateGraphicsLayer = new GraphicsLayer();
      _self.mapview.map.add(_self.udpateGraphicsLayer);
      _self.sketch = new Sketch({
        layer: _self.udpateGraphicsLayer,
        view: _self.mapview,
        // graphic will be selected as soon as it is created
        creationMode: "update",
      });
      // 设置绘图工具条显示要素
      _self.sketch.visibleElements = {
        createTools: {
          point: false,
          polyline: false,
          polygon: true,
          rectangle: false,
          circle: false,
        },
        selectionTools: {
          "lasso-selection": false,
          "rectangle-selection": false,
        },
        settingsMenu: false,
      };
      _self.sketch.create();
      _self.mapview.ui.add(_self.sketch, "top-right");
      _self.sketch.on("create", (event) => {
        if (event.state === "complete") {
          console.log("create complete");
          _self.selectedGraphic = event.graphic;
          _self.addGraphics.push(event.graphic);
          // 每个要素只有一个点，如果已创建的一个点，则不允许继续创建点。隐藏创建点按钮
          if (_self.addGraphics.length > 0)
            document.getElementsByClassName(
              "esri-sketch__section esri-sketch__tool-section"
            )[1].style.display = "none";
          // _self.mapview.graphics.add(event.graphic);
          // _self.mapview.ui.remove(_self.sketch);
        }
      });
      _self.sketch.on("update", (event) => {
        if (event.state === "complete") {
          console.log("update complete");
          if (event.graphics.length == 0) return;
          _self.selectedGraphic = event.graphics[0];
        }
      });
      _self.sketch.on("delete", (event) => {
        event.graphics.forEach((graphic) => {
          console.log("deleted", graphic);
          if (graphic == _self.selectedGraphic)
            _self.selectedGraphic = undefined;
          _self.addGraphics = _self.addGraphics.filter(
            (item) => item !== graphic
          );
        });
        // 如果没有添加任何点，就显示创建点按钮
        if (_self.addGraphics.length == 0)
          document.getElementsByClassName(
            "esri-sketch__section esri-sketch__tool-section"
          )[1].style.display = "";
      });
    },

    submitForm() {
      let _self = this;
      console.log(_self.formData);
      _self.$refs["elForm"].validate((valid) => {
        if (!valid) return;
        if (_self.selectedGraphic == undefined) {
          _self.$message.error("请添加空间位置信息");
          return;
        }
        // 新增要素
        const addFeature = new Graphic({
          geometry:
            _self.selectedGraphic == undefined
              ? ""
              : _self.selectedGraphic.geometry,
          attributes: _self.formData,
        });
        _self.featureLayer
          .applyEdits({
            addFeatures: [addFeature],
          })
          .then((editsResult) => {
            console.log(editsResult);
            // if (_self.selectedGraphic)
            //   _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
            // const objectId = editsResult.addFeatureResults[0].objectId;
            // // 根据返回的objectid添加附件
            // _self.addAttachment(attachGroupId);
            _self.$message.success("新增成功");
            _self.cancel();
          });
      });
    },
    cancel() {
      let _self = this;
      this.$refs["elForm"].resetFields();
      _self.addGraphics = [];
      // 删除临时图形
      if (_self.selectedGraphic)
        _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
      _self.mapview.graphics.removeAll();
      _self.mapview.map.layers.remove(_self.udpateGraphicsLayer);
      // 删除微件
      _self.mapview.ui.remove(_self.sketch);
      const paramObj = {
        roadcode: _self.roadcode,
        feature: _self.roadfeature,
      };
      this.toggleComponent("roadEditPanel", paramObj);
    },
    resetForm() {},
  },
};
</script>

<style lang="scss" scoped>
.title-row {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 1vh;
}
</style>
